using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;

public class Character : MonoBehaviour
{
    [Header("生命值")]
    public float maxHealth; // 最大生命值
    protected float _currentHealth; // 当前生命值
    //定义一个属性，代表玩家的生命值
    public virtual float CurrentHealth
    {
        get { return _currentHealth; }
        set { _currentHealth = value; }
    }

    [Header("无敌")]
    public float invulnerableDuration; // 无敌持续时间
    protected bool invulnerable; // 是否处于无敌状态

    public virtual void Start()
    {
        CurrentHealth = maxHealth;
    }

    // 受到伤害
    public virtual void TakeDamage(Attack attack)
    {
        if (invulnerable) return; // 如果处于无敌状态，直接返回

        SetHealth(-attack.damage);
        Hit(attack);// 触发受伤逻辑
        StartCoroutine(nameof(InvulnerableCoroutine)); // 启动无敌状态的协程
    }

    // 设置生命值
    public virtual void SetHealth(float value)
    {

        if (CurrentHealth + value >= maxHealth)//超过最大生命值
        {
            CurrentHealth = maxHealth;
        }
        else if (CurrentHealth + value <= 0)// 小于等于0
        {
            CurrentHealth = 0;
            Die(); // 触发死亡逻辑
        }
        else
        {
            CurrentHealth += value;
        }
    }

    // 受伤逻辑
    protected virtual void Hit(Attack attack) { }

    // 死亡逻辑
    protected virtual void Die() { }

    // 无敌状态的协程
    private IEnumerator InvulnerableCoroutine()
    {
        invulnerable = true; // 设置为无敌状态

        yield return new WaitForSeconds(invulnerableDuration); // 等待无敌持续时间

        invulnerable = false; // 结束无敌状态
    }
}
